package com.dragon.logical.service.contract.impl;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dragon.common.model.ResultCode;
import com.dragon.common.model.exception.CustomException;
import com.dragon.common.util.ExportUtil;
import com.dragon.logical.service.contract.IProduceProductsService;
import com.dragon.logical.service.contract.ProduceService;
import com.dragon.repository.entity.*;
import com.dragon.repository.mapper.*;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 供应商产品生产关联表 服务实现类
 * </p>
 *
 * @author sy
 * @since 2023-08-23
 */
@Service
public class ProduceProductsServiceImpl extends ServiceImpl<ProduceProductsMapper, ProduceProducts> implements IProduceProductsService {

    @Autowired
    ProduceProductsMapper mapper;
    @Autowired
    ProduceMapper produceMapper;
    @Autowired
    ProduceService produceService;
    @Autowired
    DeliverMapper deliverMapper;
    @Autowired
    OtherFileMapper fileMapper;
    @Autowired
    SchedulingSonMapper schedulingSonMapper;
    @Autowired
    EquipmentMapper equipmentMapper;



    @Override
    public List<ProduceProducts> selectList(Integer produceId,Integer page, Integer limit){
        Page<ProduceProducts> productsPage = new Page<>(page, limit);
        List<ProduceProducts> produceProducts = mapper.selectListByProduce(productsPage,produceId);
        if(produceProducts==null||produceProducts.size()==0){
            throw new CustomException(ResultCode.DATA_NOT_FOUND);
        }
        produceProducts.forEach(produceProducts1 -> {
            if (produceProducts1.getProduceStatus() == 1){
                List<SchedulingSon> sonList = schedulingSonMapper.selectList(new QueryWrapper<SchedulingSon>()
                        .lambda()
                        .eq(SchedulingSon::getProduceId, produceId)
                        .eq(SchedulingSon::getProductId, produceProducts1.getQuotesProductId()));
                if (sonList.size() != 0){
                    List<Integer> equipmentIds = sonList.stream().distinct().map(SchedulingSon::getEquipmentId).collect(Collectors.toList());
                    List<Equipment> equipmentList = equipmentMapper.selectBatchIds(equipmentIds);
                    String equipmentCode = equipmentList.stream().map(r -> r.getEquipmentCode()).collect(Collectors.joining(","));
                    produceProducts1.setEquipmentCode(equipmentCode);
                }
            }
        });

        return produceProducts;
    }


    @Override
    public List<ProduceProducts> selectProductsList(Integer deliverId, Integer page, Integer limit){
        Deliver deliver = deliverMapper.selectById(deliverId);
        List<ProduceProducts> produceProducts = selectList(deliver.getProduceId(),page,limit);
        return produceProducts;
    }


//    @Override
//    public void exportExcel(Integer produceId,HttpServletResponse response) throws UnsupportedEncodingException {
//        Produce produce = produceMapper.selectById(produceId);
//        List<ProduceProducts> produceProducts = selectList(produceId, 1, 1000);
//        List<List<Object>> rowTotal = new ArrayList<>();
//        List<Object> row1 = CollUtil.newArrayList("产品名称", "规格型号", "材质", "合同数量","已生产数量");
//        rowTotal.add(row1);
//        produceProducts.forEach(produceProducts1 -> {
//            List<Object> row = CollUtil.newArrayList(produceProducts1.getName(),produceProducts1.getSpecification(),
//                    produceProducts1.getVProductMaterial(),produceProducts1.getNum().toString(),
//                    produceProducts1.getProduceNum().toString());
//            rowTotal.add(row);
//        });
//        List<Object> row2 = CollUtil.newArrayList("合同附件");
//        rowTotal.add(row2);
//        //附件
//        List<OtherFile> otherFileList = fileMapper.selectList(new QueryWrapper<OtherFile>()
//                .lambda()
//                .eq(OtherFile::getFileType,1)
//                .eq(OtherFile::getStreamType, 2)
//                .eq(OtherFile::getCorrelationId, produce.getContractId()));
//        otherFileList.forEach(otherFile -> {
//            byte[] data = new byte[0];
//            try {
//                URL url = new URL(otherFile.getUrl());
//                //打开链接
//                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//                conn.setDoOutput(true);
//                conn.setDoInput(true);
//                //设置请求方式为"GET"
//                conn.setRequestMethod("GET");
//                //超时响应时间为5秒
//                conn.setConnectTimeout(5 * 1000);
//                //通过输入流获取图片数据
//                InputStream inStream = conn.getInputStream();
//                //得到图片的二进制数据，以二进制封装得到数据，具有通用性
//                data = ExportUtil.readInputStream(inStream);
//
//            } catch (IOException e) {
//                e.printStackTrace();
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//            List<Object> row = CollUtil.newArrayList(otherFile.getUrl());
//            rowTotal.add(row);
//        });
//        ExportUtil.exportExcel(rowTotal,response, produce.getName());
//    }

    @Override
    public void exportExcel(Integer produceId,HttpServletResponse response) throws UnsupportedEncodingException{
        Produce produce = produceMapper.selectById(produceId);
        List<ProduceProducts> produceProducts = selectList(produceId, 1, 1000);
        List<OtherFile> otherFileList = fileMapper.selectList(new QueryWrapper<OtherFile>()
                .lambda().eq(OtherFile::getStreamType, 2)
                .eq(OtherFile::getCorrelationId, produce.getContractId())
                .eq(OtherFile::getFileType,1));
        List<List<Object>> rowList = new ArrayList<List<Object>>();
        // Excel表头
        rowList.add(Arrays.asList("产品名称", "规格型号", "材质", "合同数量","已生产数量"));
        produceProducts.forEach(produceProducts1 -> {
            // 下载内容导入excel
            rowList.add(Arrays.asList(produceProducts1.getName(),produceProducts1.getSpecification(),produceProducts1.getVProductMaterial(),
                    produceProducts1.getNum(),produceProducts1.getProduceNum()));
        });
        if (otherFileList.size() != 0){
            rowList.add(Arrays.asList("附件"));
            otherFileList.forEach(otherFile -> {
                rowList.add(Arrays.asList(otherFile.getUrl()));
            });
        }
        // 接下来需要调用生成Excel的方法，唯一需要注意的是第三列的图片是一个网络URL地址，我们需要将其转成png或者img格式并嵌入到对应的Excel单元格里
        try {
            HSSFWorkbook wb = ExportUtil.warpSingleWorkbook("生产明细带附件", rowList, true);
            response.reset();
            response.setHeader("Content-type","application/octet-stream");
            response.setContentType("application/octet-stream");
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("Accept-Ranges", "bytes");
            String fileName = "带图片报表" + "_" + DateUtil.format(new Date(), "yyyyMMdd") + ".xls";
            fileName = new String(fileName.getBytes());
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
            // 文件流输出到rs里
            wb.write(response.getOutputStream());
            response.getOutputStream().flush();
            response.getOutputStream().close();
            wb.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }





    @Transactional(rollbackFor = RuntimeException.class)
    @Override
    public void updateProduceStatus(Integer id, Integer status){
        ProduceProducts produceProducts = mapper.selectById(id);
        if(produceProducts==null){
            throw new CustomException(ResultCode.DATA_NOT_FOUND);
        }
        produceProducts.setProduceStatus(status);
        mapper.updateById(produceProducts);

        //添加附件
//        List<OtherFile> otherFileList = produce1.getOtherFileList();
//        if ( otherFileList != null ){
//            otherFileList.forEach(file -> {
//                file.setStreamType(3);
//                file.setCorrelationId(produce1.getId());
//                file.setCreateTime(DateUtil.date());
//                fileMapper.insert(file);
//            });
//        }

        //查询当前是否还有其他的产品，如果没有则更改主表状态
        List<ProduceProducts> produceProducts1 = mapper.selectList(
                new LambdaQueryWrapper<ProduceProducts>().ne(ProduceProducts::getId,id)
                        .eq(ProduceProducts::getProduceId,produceProducts.getProduceId())
                        .ne(ProduceProducts::getProduceStatus,status)

        );

        Produce produce = produceMapper.selectOne(
                new QueryWrapper<Produce>().lambda().eq(Produce::getId,produceProducts.getProduceId())
        );
        if(produce == null){
            throw new CustomException(ResultCode.DATA_NOT_FOUND);
        }

        if(produceProducts1.size()==0 && status == 2){
            produce.setType(status);
            produce.setUpdateTime(DateUtil.date());
            produceMapper.updateById(produce);
        } else {
           if(status < 2 && !status.equals(produce.getType())){
               produce.setType(status);
               produce.setUpdateTime(DateUtil.date());
               produceMapper.updateById(produce);
           }
        }

//        if(status == 2){
//            QueryWrapper<ProduceProducts> queryWrapper = new QueryWrapper<>();
//            queryWrapper.lambda()
//                    .eq(ProduceProducts::getProduceId,produceProducts.getProduceId())
//                    .ne(ProduceProducts::getId,produceProducts.getId())
//                    .eq(ProduceProducts::getProduceStatus,status);
//            List<ProduceProducts> produceProducts1 = mapper.selectList(queryWrapper);
//            if(produceProducts1==null||produceProducts1.size()==0){
//                // 修改主表状态
//                produce.setType(status);
//                produce.setUpdateTime(DateUtil.date());
//                produceMapper.updateById(produce);
//                //生成数据
//                produceService.generateData(produce);
//            }
//        }

    }


    @Override
    public void enterProductNum(ProduceProducts pp){
        ProduceProducts produceProducts = mapper.selectById(pp.getId());
        if(produceProducts == null){
            throw new CustomException(ResultCode.DATA_NOT_FOUND);
        }

        //计算数量
        Integer produceNum = produceProducts.getProduceNum()+pp.getNum();
        produceProducts.setProduceNum(produceNum);
        produceProducts.setUpdateTime(DateUtil.date());

        Produce produce = produceMapper.selectOne(
                new QueryWrapper<Produce>().lambda().eq(Produce::getId,produceProducts.getProduceId())
        );

        if(produceProducts.getProduceNum() >= produceProducts.getNum()){
            //则该产品生产完成
            produceProducts.setProduceStatus(2);
            // 检测其他产品是否生产完成
            //查询当前是否还有其他的产品，如果没有则更改主表状态
            List<ProduceProducts> produceProducts1 = mapper.selectList(
                    new LambdaQueryWrapper<ProduceProducts>().ne(ProduceProducts::getId,pp.getId())
                            .eq(ProduceProducts::getProduceId,produceProducts.getProduceId())
                            .ne(ProduceProducts::getProduceStatus,2)

            );
            if(produceProducts1.size() == 0){
                if(produce==null){
                    throw new CustomException(ResultCode.DATA_NOT_FOUND);
                }
                produce.setType(2);
                produce.setUpdateTime(DateUtil.date());
                produceMapper.updateById(produce);
                List<OtherFile> otherFileList = pp.getOtherFileList();
                if (otherFileList != null) {
                    otherFileList.forEach(file -> {
                        file.setStreamType(3);
                        file.setCreateTime(DateUtil.date());
                        file.setCorrelationId(produce.getId());
                        fileMapper.insert(file);
                    });
                }
            } else {
                if(produce.getType()!=1){
                    produce.setType(1);
                    produce.setUpdateTime(DateUtil.date());
                    produceMapper.updateById(produce);
                }
            }
        } else {
            produceProducts.setProduceStatus(1);
            
            if(produce==null){
                throw new CustomException(ResultCode.DATA_NOT_FOUND);
            }
            if(produce.getType()!=1){
                produce.setType(1);
                produce.setUpdateTime(DateUtil.date());
                produceMapper.updateById(produce);
            }
        }
        mapper.updateById(produceProducts);
    }

}
